<template>
  <div class="multi-dim-report">
    <!-- 维度选择与操作 -->
    <el-card class="mb-4" shadow="never">
      <el-form :inline="true" size="small">
        <el-form-item label="报表维度">
          <el-select v-model="dimension" style="width:150px">
            <el-option label="采购统计" value="purchase"/>
            <el-option label="库存统计" value="stock"/>
            <el-option label="工序统计" value="process"/>
            <el-option label="供应商统计" value="supplier"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="dimension==='purchase'" label="采购单号">
          <el-input v-model="search.purchaseNo" clearable placeholder="采购单号"/>
        </el-form-item>
        <el-form-item v-if="dimension==='stock'" label="物料名称">
          <el-input v-model="search.material" clearable placeholder="物料名称"/>
        </el-form-item>
        <el-form-item v-if="dimension==='process'" label="工序名称">
          <el-input v-model="search.processName" clearable placeholder="工序名称"/>
        </el-form-item>
        <el-form-item v-if="dimension==='supplier'" label="供应商">
          <el-input v-model="search.supplier" clearable placeholder="供应商名称"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="exportExcel">导出Excel</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图表区 -->
    <el-card class="mb-4" shadow="never">
      <div ref="chartRef" style="width:100%;height:320px"></div>
    </el-card>

    <!-- 多维报表表格 -->
    <el-table :data="filteredData" border style="width:100%;">
      <el-table-column v-for="col in columns" :key="col.prop" :prop="col.prop" :label="col.label" :width="col.width"/>
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'
import * as echarts from 'echarts'

const dimension = ref('purchase')
const search = ref({
  purchaseNo: '',
  material: '',
  processName: '',
  supplier: ''
})

// 生成15条模拟数据/维度
function genPurchase() {
  const sups = ['国药集团','华润药业','恒瑞医药','复星医药','齐鲁制药']
  const mats = ['对乙酰氨基酚','头孢拉定原料','乳糖','阿莫西林','葡萄糖']
  let arr = []
  for (let i = 0; i < 15; i++) {
    arr.push({
      purchaseNo: 'CG20240'+(100+i),
      supplier: sups[i%5],
      material: mats[i%5],
      qty: Math.floor(Math.random()*4000)+500,
      price: (Math.random()*15+2).toFixed(2),
      date: `2025-06-${String(i%28+1).padStart(2,'0')}`
    })
  }
  return arr
}
function genStock() {
  const mats = ['对乙酰氨基酚','乳糖','葡萄糖','塑料瓶','说明书','头孢拉定原料','阿莫西林','氯化钠','包材A','包材B','瓶盖','PVC板','泡罩']
  const cat = ['原料','辅料','包材','成品']
  let arr = []
  for(let i=0;i<15;i++){
    arr.push({
      material: mats[i%mats.length],
      code: 'MAT'+(10000+i),
      category: cat[i%4],
      unit: ['kg','kg','kg','个','份','kg','kg','kg','箱','箱','个','片','个'][i%mats.length],
      stock: Math.floor(Math.random()*9000)+100,
      warning: Math.floor(Math.random()*1000)+100,
      onway: Math.floor(Math.random()*300)
    })
  }
  return arr
}
function genProcess() {
  const procs = ['混合','制粒','压片','包衣','包装','称量','质检']
  let arr = []
  for(let i=0;i<15;i++){
    arr.push({
      processName: procs[i%procs.length],
      totalTask: Math.floor(Math.random()*40)+20,
      okCount: Math.floor(Math.random()*40)+15,
      ngCount: Math.floor(Math.random()*3),
      avgTime: '00:' + String(Math.floor(Math.random()*40)+10).padStart(2,'0')
    })
  }
  return arr
}
function genSupplier() {
  const sups = ['国药集团','恒瑞医药','华润药业','复星医药','齐鲁制药','扬子江药业','正大天晴','科伦药业']
  let arr = []
  for(let i=0;i<15;i++){
    arr.push({
      supplier: sups[i%sups.length],
      totalOrder: Math.floor(Math.random()*30)+5,
      totalQty: Math.floor(Math.random()*40000)+3000,
      passRate: (Math.random()*2+97).toFixed(2)+'%',
      delayRate: (Math.random()*2).toFixed(2)+'%'
    })
  }
  return arr
}

const dataMap = {
  purchase: genPurchase(),
  stock: genStock(),
  process: genProcess(),
  supplier: genSupplier()
}

const columnMap = {
  purchase: [
    { prop: 'purchaseNo', label: '采购单号', width: 120 },
    { prop: 'supplier', label: '供应商', width: 120 },
    { prop: 'material', label: '物料名称', width: 120 },
    { prop: 'qty', label: '采购数量', width: 100 },
    { prop: 'price', label: '单价', width: 80 },
    { prop: 'date', label: '采购日期', width: 110 }
  ],
  stock: [
    { prop: 'material', label: '物料名称', width: 130 },
    { prop: 'code', label: '物料编码', width: 120 },
    { prop: 'category', label: '类别', width: 100 },
    { prop: 'unit', label: '单位', width: 80 },
    { prop: 'stock', label: '库存', width: 100 },
    { prop: 'warning', label: '预警库存', width: 100 },
    { prop: 'onway', label: '在途数量', width: 100 }
  ],
  process: [
    { prop: 'processName', label: '工序名称', width: 120 },
    { prop: 'totalTask', label: '总任务数', width: 100 },
    { prop: 'okCount', label: '合格数', width: 100 },
    { prop: 'ngCount', label: '不合格数', width: 100 },
    { prop: 'avgTime', label: '平均用时', width: 110 }
  ],
  supplier: [
    { prop: 'supplier', label: '供应商', width: 120 },
    { prop: 'totalOrder', label: '采购订单数', width: 120 },
    { prop: 'totalQty', label: '采购总量', width: 110 },
    { prop: 'passRate', label: '合格率', width: 100 },
    { prop: 'delayRate', label: '延迟率', width: 100 }
  ]
}

const columns = computed(() => columnMap[dimension.value])
const rawData = computed(() => dataMap[dimension.value])

const filteredData = computed(() => {
  if (dimension.value === 'purchase') {
    return rawData.value.filter(row => !search.value.purchaseNo || row.purchaseNo.includes(search.value.purchaseNo))
  } else if (dimension.value === 'stock') {
    return rawData.value.filter(row => !search.value.material || row.material.includes(search.value.material))
  } else if (dimension.value === 'process') {
    return rawData.value.filter(row => !search.value.processName || row.processName.includes(search.value.processName))
  } else if (dimension.value === 'supplier') {
    return rawData.value.filter(row => !search.value.supplier || row.supplier.includes(search.value.supplier))
  }
  return rawData.value
})

function doSearch() {}
function resetSearch() {
  search.value = { purchaseNo: '', material: '', processName: '', supplier: '' }
}

// --- 导出 Excel ---
function exportExcel() {
  const heads = columns.value.map(col => col.label)
  const fields = columns.value.map(col => col.prop)
  const body = filteredData.value.map(row => fields.map(f => row[f]))
  const ws = XLSX.utils.aoa_to_sheet([heads, ...body])
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '多维报表')
  XLSX.writeFile(wb, '多维统计报表.xlsx')
  ElMessage.success('已导出Excel')
}

// --- 统计图 ---
const chartRef = ref()
let chartIns = null

function chartOption() {
  if (dimension.value === 'purchase') {
    // 采购数量TOP10
    const sorted = [...filteredData.value].sort((a,b)=>b.qty-a.qty).slice(0,10)
    return {
      title: { text: '采购数量TOP10', left: 20, top: 0, textStyle: { fontSize: 15 }},
      grid: { left: 60, right: 30, bottom: 40, top: 50 },
      xAxis: { type: 'category', data: sorted.map(i=>i.material+'-'+i.purchaseNo) },
      yAxis: { type: 'value', name: '数量' },
      tooltip: { trigger: 'axis' },
      series: [{
        type: 'bar',
        data: sorted.map(i=>i.qty),
        barMaxWidth: 36,
        itemStyle: { color: '#49B1F5' }
      }]
    }
  }
  if (dimension.value === 'stock') {
    // 实时库存TOP10
    const sorted = [...filteredData.value].sort((a,b)=>b.stock-a.stock).slice(0,10)
    return {
      title: { text: '库存数量TOP10', left: 20, top: 0, textStyle: { fontSize: 15 }},
      grid: { left: 60, right: 30, bottom: 40, top: 50 },
      xAxis: { type: 'category', data: sorted.map(i=>i.material) },
      yAxis: { type: 'value', name: '库存' },
      tooltip: { trigger: 'axis' },
      series: [{
        type: 'bar',
        data: sorted.map(i=>i.stock),
        barMaxWidth: 36,
        itemStyle: { color: '#6DD9A7' }
      }]
    }
  }
  if (dimension.value === 'process') {
    // 工序合格率折线
    const data = filteredData.value.slice(0,10)
    return {
      title: { text: '工序合格率', left: 20, top: 0, textStyle: { fontSize: 15 }},
      grid: { left: 60, right: 30, bottom: 40, top: 50 },
      xAxis: { type: 'category', data: data.map(i=>i.processName) },
      yAxis: { type: 'value', name: '合格率(%)', min: 0, max: 100 },
      tooltip: { trigger: 'axis' },
      series: [{
        type: 'line',
        data: data.map(i=>Math.round(i.okCount/(i.totalTask||1)*100)),
        symbol: 'circle',
        symbolSize: 10,
        lineStyle: { width: 3, color: '#FFD877' },
        itemStyle: { color: '#FFD877' },
        areaStyle: { opacity: 0.13 }
      }]
    }
  }
  if (dimension.value === 'supplier') {
    // 供应商合格率饼图
    const data = filteredData.value.slice(0,8)
    return {
      title: { text: '供应商合格率分布', left: 20, top: 10, textStyle: { fontSize: 15 }},
      tooltip: { trigger: 'item' },
      legend: { bottom: 0, type: 'scroll' },
      series: [{
        type: 'pie',
        radius: ['35%','60%'],
        center: ['50%','45%'],
        label: { formatter: '{b}\n{d}%' },
        data: data.map(i=>({
          name: i.supplier,
          value: Number(i.passRate.replace('%',''))
        })),
        emphasis: { scale: true }
      }]
    }
  }
  return {}
}

function drawChart() {
  if (!chartRef.value) return
  if (!chartIns) chartIns = echarts.init(chartRef.value)
  chartIns.setOption(chartOption(), true)
  chartIns.resize()
}
onMounted(() => { nextTick(drawChart) })
watch([dimension, filteredData], () => { nextTick(drawChart) })
</script>

<style scoped>
.multi-dim-report {
  padding: 20px 16px;
}
.mb-4 { margin-bottom: 16px; }
</style>
